﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ServerManager.Data;
using ServerManager.Models;
using ServerManager.Repository;

namespace ServerManager.Controllers
{
    [Authorize]
    [Route("[controller]")]
    public class AppController : Controller
    {
        private readonly IAppRepository _appRepository;
        private readonly IRepository<Server> _serverRepository;

        public AppController(IAppRepository appRepository,
            IRepository<Server> serverRepository)
        {
            _appRepository = appRepository;
            _serverRepository = serverRepository;
        }

        public async Task<IActionResult> Index()
        {
            var list = await _appRepository.GetList();
            return View(list);
        }

        [HttpGet("[action]/{id?}")]
        public async Task<IActionResult> CreateOrUpdate(int? id)
        {
            if (id == null)
            {
                await BuildServerList();
                return View();
            }
            else
            {
                var app = _appRepository.Find(x => x.Id == id);
                await BuildServerList(app.Id);
                return View(app);
            }
        }

        [HttpPost("[action]/{id?}")]
        public async Task<IActionResult> CreateOrUpdate(int? id, App a)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    a.CreateTime = DateTime.Now;
                    await _appRepository.AddAsync(a);
                }
                else
                {
                    if (id == a.Id)
                    {
                        await _appRepository.UpdateAsync(a);
                    }
                }
            }
            return RedirectToAction(nameof(Index));
        }

        [HttpGet("[action]/{id}")]
        public async Task<IActionResult> Details(int id)
        {
            var app = await _appRepository.GetById(id);
            return View(app);
        }

        [HttpGet("[action]/{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            await _appRepository.DeleteAsync(x => x.Id == id);
            return RedirectToAction(nameof(Index));
        }

        #region help
        private async Task BuildServerList(object selected = null)
        {
            var list = await _serverRepository.TableNoTracking.OrderBy(x => x.Position).ToListAsync();

            ViewBag.ServerList = new SelectList(list, "Id", "Position", selected);
        }
        #endregion
    }
}